package com.kaver.modular.dc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.kaver.core.base.controller.BaseController;
import com.kaver.core.base.tips.ErrorTip;
import com.kaver.core.common.annotion.Permission;
import com.kaver.core.common.exception.BizExceptionEnum;
import com.kaver.core.exception.BzException;
import com.kaver.core.log.LogObjectHolder;
import com.kaver.core.node.ZTreeNode;
import com.kaver.core.page.PageBT;
import com.kaver.core.page.PageInfoBT;
import com.kaver.core.shiro.ShiroKit;
import com.kaver.core.shiro.ShiroUser;
import com.kaver.core.util.ToolUtil;
import com.kaver.modular.dc.service.IDcEnvRoleService;
import com.kaver.modular.dc.service.IDcEnvService;
import com.kaver.modular.system.model.DcEnv;
import com.kaver.modular.system.model.DcEnvRole;
import com.kaver.modular.system.service.IRoleService;

/**
 * 环境管理控制器
 *
 * @author Roc
 * @Date 2019-01-29 10:35:49
 */
@Controller
@RequestMapping("/dcEnv")
public class DcEnvController extends BaseController {

    private String PREFIX = "/dc/dcEnv/";

    @Autowired
    private IDcEnvService dcEnvService;
    @Autowired
    IRoleService roleService;
    @Autowired
    IDcEnvRoleService envRoleService;
    /**
     * 跳转到环境管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "dcEnv.html";
    }

    /**
     * 跳转到添加环境管理
     */
    @RequestMapping("/dcEnv_add")
    public String dcEnvAdd() {
        return PREFIX + "dcEnv_add.html";
    }
    /**
     * 跳转到角色分配
     */
    @RequestMapping(value = "/role_assign/{envId}")
    public String roleAssign(@PathVariable("envId") Integer envId, Model model) {
        if (ToolUtil.isEmpty(envId)) {
            throw new BzException(BizExceptionEnum.REQUEST_NULL);
        }
        DcEnv env = dcEnvService.selectById(envId);
        model.addAttribute("envId", envId);
        model.addAttribute("envName", env.getEnvName());
        return PREFIX + "dcEnv_role_assign.html";
    }
    /**
     * 获取角色列表
     */
    @RequestMapping(value = "/roleTreeListByEnvId/{envId}")
    @ResponseBody
    public List<ZTreeNode> menuTreeListByRoleId(@PathVariable Integer envId) {
        DcEnvRole entity = new DcEnvRole();
        entity.setEnvId(envId);
        Wrapper<DcEnvRole> wrapper = new EntityWrapper<DcEnvRole>(entity);
        List<DcEnvRole> dcEnvRoles = envRoleService.selectList(wrapper);
        List<Integer> roleIds = dcEnvRoles.stream().map(DcEnvRole::getRoleId).collect(Collectors.toList());
        List<ZTreeNode> roleTreeList = this.roleService.roleTreeList();
        for (ZTreeNode node : roleTreeList) {
            if (roleIds.contains(Integer.valueOf(node.getId().intValue()))) {
                node.setChecked(true);
            }
        }
        return roleTreeList;
        
    }
    /**
     * 跳转到修改环境管理
     */
    @RequestMapping("/dcEnv_update/{dcEnvId}")
    public String dcEnvUpdate(@PathVariable Integer dcEnvId, Model model) {
        DcEnv dcEnv = dcEnvService.selectById(dcEnvId);
        model.addAttribute("item",dcEnv);
        LogObjectHolder.me().set(dcEnv);
        return PREFIX + "dcEnv_edit.html";
    }

    /**
     * 获取环境管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(PageBT pageBT,String condition) {
        return new PageInfoBT<>(dcEnvService.selectPage(new Page<>(pageBT.getPageNumber(), pageBT.getPageSize()),null));
    }

    /**
     * 新增环境管理
     */
    @Permission
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(DcEnv dcEnv) {
    	DcEnv entity = new DcEnv();
		entity.setEnvName(dcEnv.getEnvName());
		Wrapper<DcEnv> wrapper = new EntityWrapper<DcEnv>(entity);
		int count = dcEnvService.selectCount(wrapper);
		if (count > 0) {
			return new ErrorTip(500, "环境名已存在");
		}
    	dcEnv.setCreateTime(new Date());
		ShiroUser user = ShiroKit.getUser();
		dcEnv.setCreateUser(user.getName());
        dcEnvService.insert(dcEnv);
        return SUCCESS_TIP;
    }
    /**
     * 新增环境角色
     */
    @Permission
    @RequestMapping(value = "/setRole")
    @ResponseBody
    public Object setRole(@RequestParam("envId") Integer envId, @RequestParam("roleIds") String roleIds) {
        ShiroUser user = ShiroKit.getUser();
        String[] ids = roleIds.split(",");
        DcEnvRole e = new DcEnvRole();
        e.setEnvId(envId);
        EntityWrapper<DcEnvRole> wrapper = new EntityWrapper<>(e);
        envRoleService.delete(wrapper);
        List<DcEnvRole> entityList = new ArrayList<>();
        for (String roleId : ids) {
            DcEnvRole dcEnvRole = new DcEnvRole();
            dcEnvRole.setCreateTime(new Date());
            dcEnvRole.setCreateUser(user.getName());
            dcEnvRole.setEnvId(envId);
            dcEnvRole.setRoleId(Integer.valueOf(roleId));
            entityList.add(dcEnvRole);
        }
        if (!CollectionUtils.isEmpty(entityList)) {
            envRoleService.insertBatch(entityList);
        }
        return SUCCESS_TIP;
    }
    /**
     * 删除环境管理
     */
    @Permission
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer dcEnvId) {
        dcEnvService.deleteById(dcEnvId);
        return SUCCESS_TIP;
    }

    /**
     * 修改环境管理
     */
    @Permission
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(DcEnv dcEnv) {
    	DcEnv env = dcEnvService.selectById(dcEnv.getId());
		if (env == null) {
			return new ErrorTip(500, "环境不存在");
		}
		if (dcEnv.getEnvName() != null && !dcEnv.getEnvName().equals(env.getEnvName())) {
			DcEnv entity = new DcEnv();
			entity.setEnvName(dcEnv.getEnvName());
			Wrapper<DcEnv> wrapper = new EntityWrapper<DcEnv>(entity);
			int count = dcEnvService.selectCount(wrapper);
			if (count > 0) {
				return new ErrorTip(500, "环境名已存在");
			}
		}
    	dcEnv.setUpdateTime(new Date());
		ShiroUser user = ShiroKit.getUser();
		dcEnv.setUpdateUser(user.getName());
        dcEnvService.updateById(dcEnv);
        return SUCCESS_TIP;
    }

    /**
     * 环境管理详情
     */
    @RequestMapping(value = "/detail/{dcEnvId}")
    @ResponseBody
    public Object detail(@PathVariable("dcEnvId") Integer dcEnvId) {
        return dcEnvService.selectById(dcEnvId);
    }
}
